package com.hopu.blb_erp.service.impl;

import com.hopu.blb_erp.entity.Functions;
import com.hopu.blb_erp.entity.Role;
import com.hopu.blb_erp.entity.User;
import com.hopu.blb_erp.service.FunctionsService;
import com.hopu.blb_erp.service.RoleService;
import com.hopu.blb_erp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private FunctionsService functionsService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(username);
        User user = userService.findByName(username);
        System.out.println(user);
        // 判断用户名是否为空
        if(user == null){
            throw new UsernameNotFoundException("用户名无效!");
        }
        // 判断用户是否被禁用
        if(!user.isState()){
            throw new RuntimeException("用户被禁用！");
        }
        // 查询角色
        List<Role> roles = roleService.findByName(username);
        // 查询权限
        List<Functions> functionsList = functionsService.findByName(username);
        // 将角色和权限拼接成字符串
        StringBuffer str = new StringBuffer();
        roles.forEach(role -> str.append("ROLE_" + role.getName() + ","));
        functionsList.forEach(fun -> str.append(fun.getName() + ","));
        str.deleteCharAt(str.length() - 1);
        // 返回用户信息和授权列表
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(str.toString()));
    }
}
